package xyz.xiaomeiqiu.study;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xyz.xiaomeiqiu.study.domain.Car;
import xyz.xiaomeiqiu.study.domain.ElectricCar;
import xyz.xiaomeiqiu.study.repository.CarRepository;

import java.util.Map;

public class App {

    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:context.xml");
        lookupInrealTime(beanFactory);

        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(App.class);
        annotationConfigApplicationContext.refresh();
        lookupCollectionByType(annotationConfigApplicationContext);
    }

    @Bean
    private ElectricCar electricCar(){
        ElectricCar electricCar = new ElectricCar();
        electricCar.setCarColor("blue");
        electricCar.setCarName("小鹏");
        electricCar.setBatteryType("氢电池");
        return electricCar;
    }

    private static void lookupInrealTime(BeanFactory beanFactory){
        CarRepository carRepository =  beanFactory.getBean("carRepository", CarRepository.class);
        System.out.println("实时查找："+ carRepository.getCars());
    }


    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, ElectricCar> beansOfType = listableBeanFactory.getBeansOfType(ElectricCar.class);
            System.out.println("查找到的所有car bean:"+beansOfType);
        }
    }
}
